OpenResty 的简单使用
OpenResty 是什么?
OpenResty 是一个强大的 Web 应用服务器,Web 开发人员可以使用 Lua 脚本语言调动 Nginx 支持的各种 C 以及 Lua 模块,更主要的是在性能方面,OpenResty可以快速构造出足以胜任 10K 以上并发连接响应的超高性能 Web 应用系统。
它封装了 Nginx,并为 Nginx 提供了高性能的可扩展程序,使 Nginx 抗压能力得到了 大大的提升,并且提供了 Lua 脚本的扩展支持,能使 Nginx 抗压能力达到 10K-1000K。
简单理解成就相当于封装了 nginx,并且集成了 LUA 脚本,开发人员只需要简单的其提供了模块就可以实现相关的逻辑,而不再像之前,还需要在 nginx 中自己编写 lua 的脚本,再进行调用了。
安装 OpenResty
添加仓库执行命令
yum install yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
执行安装
yum install openresty
安装成功后会在默认目录下:
/usr/local/openresty
这个目录里面可以使用 ./configure --help
查看更多的配置选项
默认已经安装好了nginx,在目录: /usr/local/openresty/nginx
下。
修改 /usr/local/openresty/nginx/conf/nginx.conf
,将配置文件使用的根设置为 root,目的就是将来要使用 Lua 脚本的时候,直接可以加载在 root 下的 Lua 脚本。
cd /usr/local/openresty/nginx/conf/
vim nginx.conf
这里将其改为 root 目录
使用 Lua 添加缓存
在 root 目录下创建一个 ad_update.lua
脚本,里面写入如下内容
ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")
local uri_args = ngx.req.get_uri_args()
local position = uri_args["position"] -- 获取请求路径中的 position 参数
local db = mysql:new()
db:set_timeout(1000) -- 连接数据库
local props = {
host = "192.168.200.128",
port = 3306,
database = "business",
user = "root",
password = "root"
}
local res = db:connect(props)
-- 在 Lua 里面 .. 表示拼接字符
local select_sql = "select url,image from tb_ad where status ='1' and position='"..position.."' and start_time<= NOW() AND end_time>= NOW()"
res = db:query(select_sql) -- 查询数据
db:close()
local redis = require("resty.redis") -- 连接 Redis
local red = redis:new()
red:set_timeout(2000)
local ip ="192.168.200.128"
local port = 6379
red:connect(ip,port)
red:set("ad_"..position,cjson.encode(res)) -- 更新 Redis 里面的数据
red:close()
ngx.say("{\"flag\":true,\"position\":\""..position.."\"}")
同理,这里也写一个拦截读取请求的脚本 ad_read.lua
--设置响应头类型
ngx.header.content_type="application/json;charset=utf8"
--获取请求中的参数ID
local uri_args = ngx.req.get_uri_args();
local position = uri_args["position"];
--获取本地缓存
local cache_ngx = ngx.shared.dis_cache;
--根据ID 获取本地缓存数据
local adCache = cache_ngx:get('ad_cache_'..position);
if adCache == "" or adCache == nil then
--引入redis库
local redis = require("resty.redis");
--创建redis对象
local red = redis:new()
--设置超时时间
red:set_timeout(2000)
--连接
local ok, err = red:connect("192.168.200.128", 6379)
--获取key的值
local rescontent=red:get("ad_"..position)
--输出到返回响应中
ngx.say(rescontent)
--关闭连接
red:close()
--将redis中获取到的数据存入nginx本地缓存
cache_ngx:set('ad_cache_'..position, rescontent, 10*60);
else
--nginx本地缓存中获取到数据直接输出
ngx.say(adCache)
end
然后再修改 Nginx 的虚拟主机的配置,配置拦截,如下所示,拦截了 /ad_read
和 /ad_update
请求
server {
listen 80;
server_name localhost;
charset utf-8;
#charset koi8-r;
#access_log logs/host.access.log main;
# 添加广告
location /ad_update {
content_by_lua_file /root/lua/ad_update.lua;
}
# 读取广告
location /ad_read {
content_by_lua_file /root/lua/ad_read.lua;
}
location / {
root html;
index index.html index.htm;
}
}
Reference
- 参考资料 OpenResty 官方网站